import { reqUserInfo,reqLogout, reqGetCode,reqUserRegister, reqUserLogin,reqGetUserInfo,reqUpdateUserInfo} from "@/api";
import {setToken} from "@/utils/token";
import { getToken, removeToken} from "@/utils/token";
const state = {
    code: "",
    token: getToken() || "",
    userInfo: {} 
}
const mutations = {
    GETCODE(state,code){
        state.code = code
    },
    GETTOKEN(state,token){
        state.token = token
    },
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo
        
    },
    CLEAR(state){
       state.token = "";
       state.userInfo = {};
       removeToken();
    }
}
const actions = {
  async  getCode({commit},phone){
        // 获取验证码
       let result = await reqGetCode(phone);
       if(result.code == 200){
           commit("GETCODE",result.data)
           return "ok"
       }else{
           return Promise.reject(new Error('fail'))
       }
    },
    async userRegister({commit},user){
        // 注册
       let result = await reqUserRegister(user);
       if(result.code == 200){
        
           return "ok"
       }else{
           return Promise.reject(new Error('fail'))
       }
      

    },
    // 登录
    async userLogin({commit},data){
       let result = await reqUserLogin(data);
       //服务器下发token，用户唯一标识
       //将来每次请求，都带上这个标识，就可以区分到底是哪一个用户了
       console.log(result);
       
       if(result.code == 200){
        commit("GETTOKEN",result.data.token);
        //持久化存储touken
        setToken(result.data.token);
           return "ok"
       }else{
           return Promise.reject(new Error('fail'))
       }
    },
    //获取用户信息
    async getUserInfo({commit}){
        let result = await reqUserInfo();
        
        if(result.code == 200){
            commit("GETUSERINFO",result.data)
            return "ok"
        }else{
            return Promise.reject(new Error('fail'))
        }
    },
    //退出登录
    async userLogout({commit}){
        //向服务器发请求，清除token
        let result = await reqLogout();
        if(result.code == 200){
            commit("CLEAR")
            return "ok"
        }else{
            return Promise.reject(new Error('fail'))
        }
    }
}
const getters = {
   
}
export default {
    state,
    mutations,
    actions,
    getters
}

















